package com.lry.basic.handler;

/**
 * Created by lry on 2017/5/29.
 */

/**
 * 一个线程只有一个lopper对象，prepare不为空抛异常
 */
public class Looper {
    //ThreadLocal 防止脏读
    private static ThreadLocal<Looper>mThreadLocal=new ThreadLocal<Looper>();
    public MessageQueue mQueue;
    public Looper(){
        this.mQueue=new MessageQueue();
    }
    /**
     *
     * @return 返回当前线程绑定的lopper对象
     */
    public static Looper myLooper(){
        return mThreadLocal.get();
    }

    public static void prepare(){
        Looper lopper=myLooper();
        if(lopper!=null){
            throw new RuntimeException("only one looper may be created per thread");
        }
        mThreadLocal.set(new Looper());
    }

    /**
     * 轮询器轮询消息队列
     */

    public static void loop(){
        Looper me=myLooper();
        if(me==null){
            throw new RuntimeException("No Looper:Looper.prepare()wasn't called on this thread.");
        }
        MessageQueue mQueue=me.mQueue;
        for(;;){
            Message msg=mQueue.next();
            if(msg==null){
                continue;
            }
            //转发
            msg.target.dispatherMessage(msg);
        }
    }
}
